package com.tsingteng.cosfun.base;

import java.util.Random;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tsingteng.cosfun.MainActivity;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.bean.NotifictionNumerBean;
import com.tsingteng.cosfun.bean.YMNotificationBean;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.ui.message.CommonActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.DBUtils;
import com.tsingteng.cosfun.utils.StringUtils;
import com.umeng.message.UTrack;
import com.umeng.message.entity.UMessage;

import org.json.JSONException;
import org.json.JSONObject;
/**
 * 通知服务
 * 常胜
 * 2018.8.30
 * */
public class NotificationService extends Service {
    private static final String TAG = UmengNotificationService.class.getName();
    public static UMessage oldMessage = null;
    private String type;
    private YMNotificationBean ymNotificationBean;
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        String message = intent.getStringExtra("UmengMsg");
        try {
            UMessage msg = new UMessage(new JSONObject(message));
            if (oldMessage != null) {
                UTrack.getInstance(getApplicationContext()).setClearPrevMessage(true);
                UTrack.getInstance(getApplicationContext()).trackMsgDismissed(oldMessage);
            }
            showNotification(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void showNotification(UMessage msg) {
        int id = new Random(System.nanoTime()).nextInt();

        String huawiid = "my_channel_01";
        String name="我是渠道名字";


        oldMessage = msg;
        Log.e("TAG","友盟返回信息打印custom："+msg.custom);
        Log.e("TAG","友盟返回信息打印title："+msg.title);
        Log.e("TAG","友盟返回信息打印text："+msg.text);
        String custom = msg.custom;
        Gson gson = new Gson();
        ymNotificationBean = gson.fromJson(custom, YMNotificationBean.class);
        type = ymNotificationBean.getType();
//        NotifictionNumerBean notifictionNumerBean = new NotifictionNumerBean();
//        notifictionNumerBean.setTime(ymNotificationBean.getTimeStamp());
//        notifictionNumerBean.setContent(ymNotificationBean.getContent());
//        notifictionNumerBean.setCount(1);
//        notifictionNumerBean.setType(ymNotificationBean.getType());
//        notifictionNumerBean.setPrifidId(ymNotificationBean.getProfileId());
//        DBUtils.addNotifiction(notifictionNumerBean);

        AppUtils.setMessageNumber(type,1);
        Notification notification = null;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(huawiid, name, NotificationManager.IMPORTANCE_LOW);
//            Toast.makeText(this, mChannel.toString(), Toast.LENGTH_SHORT).show();
            Log.i(TAG, mChannel.toString());
            manager.createNotificationChannel(mChannel);
            if(notification == null){
                notification = new Notification.Builder(this)
                        .setChannelId(huawiid)
                        .setContentTitle(msg.title)
                        .setSmallIcon(R.mipmap.ic_launcher_round)
                        .setContentText(msg.text)
                        .build();
            }
        }else {
            manager.cancelAll();
            Notification.Builder mBuilder = new Notification.Builder(this);
            mBuilder.setContentTitle(msg.title)
                    .setContentText(msg.text)
                    .setTicker(msg.ticker)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setAutoCancel(true);
            if(notification == null){
                notification = mBuilder.getNotification();
            }
        }
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.number+=1;
        Log.e("常胜",notification.number+"");
        PendingIntent clickPendingIntent = getClickPendingIntent(this, msg);
        PendingIntent dismissPendingIntent = getDismissPendingIntent(this, msg);
        notification.deleteIntent = dismissPendingIntent;
        notification.contentIntent = clickPendingIntent;
        manager.notify(id, notification);
    }

    public PendingIntent getClickPendingIntent(Context context, UMessage msg) {
        Intent clickIntent = new Intent();
        if (StringUtils.isForeground(context,"MainActivity")) {
            clickIntent.setClass(context, CommonActivity.class);
            if ("POINT".equals(type)) {
                //@我
                clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_AT_ME);
                clickIntent.putExtra("funType", "POINT");
                clickIntent.putExtra("biao", 2);
            } else if ("REVIEW".equals(type)) {
                //评论我
                clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_COMMENT);
                clickIntent.putExtra("funType", "REVIEW");
                clickIntent.putExtra("biao", 1);
            } else if ("FAVOR".equals(type)) {
                //赞我
                clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_GREAT);
                clickIntent.putExtra("funType", "FAVOR");
                clickIntent.putExtra("biao", 0);
            } else if ("FANS".equals(type)) {
                //粉丝
                clickIntent.putExtra(CommonActivity.FRAGMENT_KEY, CommonActivity.KEY_FANS);
                clickIntent.putExtra("funType", "FANS");
            } else if ("NOTICE".equals(type)) {
                //系统通知
                clickIntent.putExtra("CommonActivity.FRAGMENT_KEY", CommonActivity.KEY_JUMP_SYSTEM);

            } else if ("HELPER".equals(type)) {
                //官方助手
                clickIntent.putExtra("CommonActivity.FRAGMENT_KEY", CommonActivity.KEY_JUMP_OFFICAL);
            } else {
                clickIntent.putExtra("CommonActivity.FRAGMENT_KEY", CommonActivity.KEY_JUMP_SYSTEM);
            }
        }else{
            clickIntent.setClass(context, MainActivity.class);
            clickIntent.putExtra(Constant.NOTIFICATION,type);
        }
       clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        clickIntent.putExtra(NotificationBroadcast.EXTRA_KEY_MSG,
                msg.getRaw().toString());
        clickIntent.putExtra(NotificationBroadcast.EXTRA_KEY_ACTION,
                NotificationBroadcast.ACTION_CLICK);
        PendingIntent clickPendingIntent = PendingIntent.getActivity(context,
                (int) (System.currentTimeMillis()),
                clickIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        return clickPendingIntent;
    }

    public PendingIntent getDismissPendingIntent(Context context, UMessage msg) {
        Intent deleteIntent = new Intent();
        deleteIntent.setClass(context, NotificationBroadcast.class);
        deleteIntent.putExtra(NotificationBroadcast.EXTRA_KEY_MSG,
                msg.getRaw().toString());
        deleteIntent.putExtra(
                NotificationBroadcast.EXTRA_KEY_ACTION,
                NotificationBroadcast.ACTION_DISMISS);
        PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context,
                (int) (System.currentTimeMillis() + 1),
                deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        return deletePendingIntent;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
